<?php



if (!defined('EXPONENT')) exit('');

$image = null;
if (isset($_POST['id'])) {
	$image = $db->selectObject('imagegallery_image','id='.$_POST['id']);
} else {
	$image->gallery_id = $_POST['parent'];
}

if (isset($_POST['gid'])) {
	$image->gallery_id = $_POST['gid'];
}

$gallery = $db->selectObject('imagegallery_gallery','id='.$image->gallery_id);
$loc = unserialize($gallery->location_data);
$loc->int = $gallery->id;

if (exponent_permissions_check('manage',$loc)) {
	$image = imagegallery_image::update($_POST,$image);
	
	// Re-order for ranking
	if (isset($image->id)) {
		// changed rank for an existing image
		if ($_POST['rank'] < $image->rank) {
			// New rank is before the current rank. Item moved up
			$db->increment('imagegallery_image','rank',1,'gallery_id='.$image->gallery_id.' AND rank >= '.$_POST['rank'] . ' AND rank < ' . $image->rank);
		} else if ($_POST['rank'] > $image->rank) {
			// New rank is after the current rank. Item moved down
			$db->decrement('imagegallery_image','rank',1,'gallery_id='.$image->gallery_id.' AND rank < '.$_POST['rank'] . ' AND rank >= ' . $image->rank);
			$_POST['rank']--;
		}
		// Rank didn't change
		$image->rank = $_POST['rank'];
	} else {
		$image->rank = $_POST['rank'];
		$db->increment('imagegallery_image','rank',1,"gallery_id=".$image->gallery_id." AND rank >= ".$_POST['rank'] . " AND rank < " . $image->rank);
	}
	$loc = unserialize($gallery->location_data);
	// 9/9/2009; immanuel192 remove file update becase we use ajax file selector
	if (isset($image->id)) {
		$db->updateObject($image,'imagegallery_image');
	} else {
		$image->posted = time();
		$db->insertObject($image,"imagegallery_image");
	}
	exponent_flow_redirect();
} else {
	echo SITE_403_HTML;
}

?>